package com.ovopark.organize.server.util;

import com.alibaba.fastjson.JSON;
import com.ovopark.organize.server.common.constant.ConstanComment;
import com.ovopark.organize.server.model.entity.Location;
import com.ovopark.organize.server.model.entity.SysParams;
import com.ovopark.organize.server.model.entity.Users;
import com.ovopark.organize.server.model.query.JsonResult;
import com.ovopark.shopweb.model.DeviceProductAreaShield;
import com.ovopark.shopweb.pojo.ClientInfo;
import net.sf.json.JSONArray;
import org.apache.commons.lang.StringUtils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtil {
	private static final Integer EARTH_RADIUS = 6371;

//	private static SysParamsService sysParamsService = (SysParamsService) ServiceUtil.getSysParamsService();

	/**
	 * 生成用户token
	 */
	public static String generateToken(Users user) {
		//id password date
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		Long expiredTime = Long.parseLong(Constant.map.get("expiredTime"));
//		String content = user.getId().toString()+","+user.getUser_name()+","+user.getPassword()+","+sdf.format(new Date())+","+expiredTime;
		String content = user.getId().toString()+","+user.getUserName()+","+user.getPassword();
//		String content = user.getId().toString();
		return AesUtil.encrypttoStr(content, "kedacom.com");
	}
	
	/**
	 * 生成永久有效token，ovostation用
	 * @param user
	 * @return
	 */
	public static String generateEternalToken(Users user) {
		String content = user.getId().toString();
		return AesUtil.encrypttoStr(content, "kedacom.com");
	}
	
	public static void main(String[]args) throws ParseException {
		Users user = new Users();
		user.setId(326450);
		System.out.println(generateEternalToken(user));
		System.out.print(decodeToken("D5B8C1436EE0E8698D87F4E34B47322E"));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String before = "1234"+","+"aaaa"+","+sdf.format(new Date());
		String content = AesUtil.encrypttoStr(before, "kedacom.com");
		System.out.println(content);

		String result = new String(AesUtil.decrypt(content, "kedacom.com"));
		System.out.println(result);
		String[] token = {};
		Integer userId;
		String password;
		Date date;
		if(StringUtils.isNotBlank(result)){
			token = result.split(",");
			if(token.length==3){
				userId = Integer.parseInt(token[0]);
				password = token[1];
				date = sdf.parse(token[2]);
				System.out.println(userId);
				System.out.println(password);
				System.out.println(date);
			}
		}
	}

	public static Object findByIdFromList(List list, Integer id) {
		for (Object obj : list) {
			try {
				Method method = obj.getClass().getMethod("getId");
				Integer objId = (Integer)method.invoke(obj);
				if (objId.equals(id)) {
					return obj;
				}
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	/**
	 * 使用新规则，创建腾讯云账号
	 * @param user
	 * @return
	 */
	public static String createTlsUserName(Users user,String environment) {
//		return user.getUser_name();
		String enrivonment = environment;
//		if(sysParamsService != null) {
		SysParams sysParams = ConstanComment.getSysParam();
		if (sysParams != null) {
			enrivonment = sysParams.getEnvironment();
		}
//		}
		// 设置一个默认值
		if (enrivonment == null) {
			enrivonment = "dev";
		}
		return enrivonment + "_" + user.getId();
	}

	/**
	 * 使用新规则，创建腾讯云账号
	 * @param user
	 * @return
	 */
	public static String createTlsUserNameByUserId(Integer userId,String environment) {
//		return user.getUser_name();
		String enrivonment = environment;
//		if(sysParamsService != null) {
			SysParams sysParams = ConstanComment.getSysParam();
		if (sysParams != null) {
			enrivonment = sysParams.getEnvironment();
		}
//		}
		// 设置一个默认值
		if (enrivonment == null) {
			enrivonment = "dev";
		}
		return enrivonment + "_" + userId;
	}



//	public static String decodeToken(String token) {
//		if (token == null || "".equals(token)){
//			return "-1";
//		}
//		try {
//			byte[] chars = AesUtil.decrypt(token, "kedacom.com");
//			if (chars != null && chars.length > 0) {
//				return new String(AesUtil.decrypt(token, "kedacom.com"));
//			} else {
//				return "-1";
//			}
//		} catch (Exception e) {
//			return "-1";
//		}
//	}
	
	public static ClientInfo decodeToken(String token) {
		ClientInfo clientInfo = new ClientInfo();
		if (StringUtils.isEmpty(token)){
			clientInfo.setResult(JsonResult.RESULT_INVALID_TOKEN);
			return clientInfo;
		}
		try {
			byte[] chars = AesUtil.decrypt(token, "kedacom.com");
			if (chars != null && chars.length > 0) {
				String result = new String(AesUtil.decrypt(token, "kedacom.com"));
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String[] array = {};
				array = result.split(",");
				if(array.length >= 3){
					clientInfo.setUserId(Integer.parseInt(array[0]));
					clientInfo.setUserName(array[1]);
					clientInfo.setPassword(array[2]);//未使用
					if (array.length >= 5) {
						clientInfo.setDate(sdf.parse(array[3]));
						clientInfo.setExpires(Long.parseLong(array[4]));
					}
				// 兼容原来版本，token只保存userId
				// 直接不兼容原来的版本
				}else if(array.length==1){
					clientInfo.setUserId(Integer.parseInt(array[0]));
//					tokenBo.setResult(JsonResult.RESULT_TOKEN_EXPIRED);
				}else{
					clientInfo.setResult(JsonResult.RESULT_INVALID_TOKEN);
				}
			} else {
				clientInfo.setResult(JsonResult.RESULT_INVALID_TOKEN);
			}
		} catch (Exception e) {
			clientInfo.setResult(JsonResult.RESULT_INVALID_TOKEN);
		}
		return clientInfo;
	}

	public static String createActivateCode(int length) {
		String base = "abcdefghijklmnopqrstuvwxyz123456789"; // 生成字符串从此序列中取
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	/**
	 * 验证邮箱地址是否正确
	 * 
	 * @param email
	 * @return
	 */
	public static boolean checkEmail(String email) {
		boolean flag = false;
		try {
			String check = "^([a-z0-9A-Z_]+[_-|\\.-]?)+[a-z0-9A-Z_]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
			Pattern regex = Pattern.compile(check);
			Matcher matcher = regex.matcher(email);
			flag = matcher.matches();
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}

		return flag;
	}

	/**
	 * 验证手机号码
	 * 
	 * @param mobiles
	 * @return
	 */
	public static boolean isMobileNO(String mobiles) {
		boolean flag = false;
		try {
//			Pattern p = Pattern
//					.compile("^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\\d{8}$");
			Pattern p = Pattern
					.compile("^1\\d{10}$");
			Matcher m = p.matcher(mobiles);
			flag = m.matches();
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}
		return flag;
	}
	
//	public static String getServer(String path) {
//		// 获取服务器信息
//		HttpServletRequest request = ServletActionContext.getRequest();
//		String projectName = path != null ? "/" + path : request.getContextPath();
//		String server = null;
//		if (request.getServerPort() == 80) {
//			server = request.getServerName() + projectName;
//		} else {
//			server = request.getServerName() + ":" + request.getServerPort() + projectName;
//		}
//		
//		return "http://" + server;
//	}
	
	public static List<Location> getLocationSquare(double latitude, double longitude, double radius) {
		List<Location> locations = new ArrayList<Location>();
		double dLongitude = 2 * Math.asin(Math.sin(radius / (2 * EARTH_RADIUS)) / Math.cos(latitude));
		dLongitude = radToDeg(dLongitude);
		
		double dLatitude = radius / EARTH_RADIUS;
		dLatitude = radToDeg(dLatitude);
		
		// 最小
		locations.add(new Location(latitude - dLatitude, longitude - dLongitude));
		// 最大
		locations.add(new Location(latitude + dLatitude, longitude + dLongitude));
		
		return locations;
	}
	
	public static ResourceBundle getUserResourceBundle(Users user) {
		ResourceBundle bundle = null;
		if("en".equals(user.getLocalelan())){
			bundle = ResourceBundle.getBundle("globalMessages", Locale.US);
		} else {
			bundle = ResourceBundle.getBundle("globalMessages", Locale.SIMPLIFIED_CHINESE);
		}
		return bundle;
	}
	
//	private static double degToRad(double degree) {
//		return degree * Math.PI / 180;
//	}
	
	private static double radToDeg(double radius) {
		return radius * 180 / Math.PI;
	}

	/**
	 * 根据逗号分割的字符串获取id列表
	 * @param idStr
	 * @return
	 */
	public static List<Integer> createList(String idStr) {
		List<Integer> result = new ArrayList<Integer>();
		if (idStr != null) {
			String[] array = idStr.split(",");
			for (String id : array) {
				if(StringUtils.isNotBlank(id)){
					result.add(Integer.parseInt(id.trim()));
				}
			}
		}
		return result;
	}
	
	/**
	 * 
	 * @param list
	 * @param separator
	 * @return
	 */
	public static String listToString(List list, char separator) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < list.size(); i++) {
			sb.append(list.get(i)).append(separator);
		}
		return list.isEmpty() ? "" : sb.toString().substring(0, sb.toString().length() - 1);
	}
	
	/**
	 * 根据逗号分割的字符串获取id列表
	 * @param idStr
	 * @return
	 */
	public static List<String> createStrList(String idStr) {
		List<String> result = new ArrayList<String>();
		if (idStr != null) {
			String[] array = idStr.split(",");
			for (String id : array) {
				if(StringUtils.isNotBlank(id)){
					result.add(id);
				}
			}
		}
		return result;
	}
	
	public static double getDistance(double longt1, double lat1, double longt2, double lat2) {
		double x, y, distance;
		x = (longt2 - longt1) * Math.PI * EARTH_RADIUS * Math.cos(((lat1 + lat2) / 2) * Math.PI / 180) / 180;
		y = (lat2 - lat1) * Math.PI * EARTH_RADIUS / 180;
		// System.out.println((Math.hypot(x, y) / 1000));
		// distance = Double.parseDouble(String.format("%.0f", Math.hypot(x, y)
		// / 1000));
		distance = Math.hypot(x, y) * 1000;
		return distance;
	}
	
	/**
	 * 根据字符串生成一个二维数组，热点用
	 * @param data
	 * @return
	 */
	public static int[][] createDoubleArray(String data) {
		int[][] blocks = new int[240][320];
		String[] lines = data.split("\n");
		for (int i = 0; i < blocks.length; i++) {
			String line = lines[i];
			if (StringUtils.isNotEmpty(line)) {
				String[] columns = line.split(" ");
				for (int j = 0; j < columns.length; j++) {
					blocks[i][j] = Integer.parseInt(columns[j]);
				}
			}
		}
		return blocks;
	}
	/**
	 * @param obj
	 * @return
	 * @author huanglt
	 */
	public static Map<String, Object> transBean2Map(Object obj) {  
        if(obj == null){  
            return new HashMap<String, Object>();
        }          
        Map<String, Object> map = new HashMap<String, Object>();  
        try {  
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());  
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();  
            for (PropertyDescriptor property : propertyDescriptors) {  
                String key = property.getName();  
                if (!key.equals("class")) {  
                    Method getter = property.getReadMethod();  
                    Object value = getter.invoke(obj);  
                    map.put(key, value);  
                }  
  
            }  
        } catch (Exception e) {  
        	e.printStackTrace();
        }  
  
        return map;  
  
    }
	
	/**
	 * 热点屏蔽区域用
	 * 坐标转数组
	 * @param shieldPoints
	 * @return
	 */
	public static int[] getShieldArr (List<DeviceProductAreaShield> shieldPoints) {
		List<Integer> rlist = new ArrayList<>();
		for (DeviceProductAreaShield item : shieldPoints) {
			String points = item.getPoints();
			StringUtils.substring(points, 2, points.length() -2);
			if (StringUtils.isNotBlank(item.getPoints())) {
				List<String> list = JSON.parseArray(points, String.class);
				List<String> point1 = JSON.parseArray(list.get(0), String.class);
				List<String> point3 = JSON.parseArray(list.get(2), String.class);
				rlist.add(Integer.parseInt(point1.get(0)));
				rlist.add(Integer.parseInt(point1.get(1)));
				rlist.add(Integer.parseInt(point3.get(0)) - Integer.parseInt(point1.get(0)));
				rlist.add(Integer.parseInt(point3.get(1)) - Integer.parseInt(point1.get(1)));
			}
		}
		int [] arr = new int[rlist.size()];

		for (int i=0;i<rlist.size();i++) {
			arr[i] = rlist.get(i);
		}
		
		return arr;
	}


	/**
	 * 热点屏蔽区域用
	 * 坐标转数组 加入坐标个数
	 * @param shieldPoints
	 * @return
	 */
	public static int[] getShieldArr1 (List<DeviceProductAreaShield> shieldPoints) {
		List<Integer> list = new ArrayList<>();
		for (DeviceProductAreaShield item : shieldPoints) {
			String points = item.getPoints();
			JSONArray arry = JSONArray.fromObject(points);
			list.add(arry.size());
			for (int i = 0; i < arry.size(); i++) {
				JSONArray inArry = JSONArray.fromObject(arry.get(i));
				for (int j = 0; j< inArry.size(); j++) {
					list.add(inArry.getInt(j));
				}
			}
		}
		int [] result  = new int[list.size()];
		for (int i=0;i<result.length;i++) {
			result[i] = list.get(i);
		}

		return result;
	}

	public static List<List<Integer>> splitList(List<Integer> list, int len) {
		if (list == null || list.size() == 0 || len < 1) {
			return null;
		}
		List<List<Integer>> result = new ArrayList<List<Integer>>();
		int size = list.size();
		int count = (size + len - 1) / len;
		for (int i = 0; i < count; i++) {
			List<Integer> subList = list.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
			result.add(subList);
		}
		return result;
	}

	/**
	 * 分页
	 * @param list
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 */
	public static List pagination(List list, Integer pageNumber, Integer pageSize) {
		if (list == null || list.size() == 0 || pageNumber == null || pageNumber == null) {
			return null;
		}
		int first = (pageNumber - 1) * pageSize;
		int size = pageSize;
		first = Math.min(first, list.size());
		int end = Math.min(first + size, list.size());
		list = list.subList(first, end);
		return list;
	}


	/**
	 * 获取区划短码
	 * @param code
	 * @return
	 * @author huanglt
	 */
	public static String  getShortCode(String code){
		if(null == code || "".equals(code)){
			return null;
		}
		String shortCode = null;
		for(int i=code.length()-2;i>=0; i=i-2){
			if("00".equals(code.substring(i, i+2))){
				if(i==0){
					shortCode = "";
					break;
				}else{
					continue;
				}
			}else{
				shortCode = code.substring(0,i+2);
				break;
			}
		}
		return shortCode;
	}

	public static String IntegerToStringSql(List<Integer> idList){
		String ids =null;
		if(CollectionUtil.isNotEmpty(idList)){
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < idList.size(); i++) {
				if(idList.get(i) !=null){
					sb.append(idList.get(i)).append(",");
				}

			}

				ids = "("+ sb.substring(0, sb.length() - 1)+")";


		}
		return ids;
	}
	public static String StringrToStringSql(List<String> idList){
		String ids =null;
		if(CollectionUtil.isNotEmpty(idList)){
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < idList.size(); i++) {
				if(StringUtils.isNotEmpty(idList.get(i))){
					sb.append("'"+idList.get(i)+"'").append(",");
				}
			}

				ids = "("+ sb.toString().substring(0, sb.toString().length() - 1)+")";


		}
		return ids;
	}
	public static String LongToStringSql(List<Long> idList){
		String ids =null;
		if(CollectionUtil.isNotEmpty(idList)){
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < idList.size(); i++) {
				if(idList.get(i) !=null){
					sb.append(idList.get(i)).append(",");
				}

			}

			ids = "("+ sb.substring(0, sb.length() - 1)+")";


		}
		return ids;
	}
}
